package com.ihighest.app.infox.activity;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;

import widget.OnWheelChangedListener;
import widget.WheelView;
import widget.adapters.ArrayWheelAdapter;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;

import com.baidu.location.LocationClient;
import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.AKGridView;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.AudioRecorder;
import com.ihighest.app.infox.myview.RecordImage;
import com.ihighest.app.infox.tools.LoopListener;
import com.ihighest.app.infox.tools.LoopView;

public class AskQuestionActivity extends ChooseAddressBaseActivity implements OnClickListener, OnWheelChangedListener {
	public static LocationClient mLocationClient = null;
	private ActivityTitle title;
	private TextView locationTextView;
	private EditText contentEditText, plantnameEditText, weatherEditText, usewhatEditText, goldEditText;
	private PopupWindow mPopupWindow;
	private android.widget.RelativeLayout.LayoutParams layoutParams;
	private LinearLayout rootview;
	private LoopView loopView;
	// private ArrayList<String> list;
	private String a;
	private ArrayList<String> listweather;
	private ArrayList<String> listname;
	private LinearLayout rootparent;
	private ArrayList<String> listmeasure;
	// private ArrayList<String> listglobe;
	private String location = "0:0:0";
	String city;

	private ArrayList<File> files;

	private int c;// 点击pop窗口的填充位置

	private File audioFile;

	MediaPlayer player;
	AudioRecorder audioRecorder;

	private static final int TAKE_TAKEPHOTO = 0x000001;
	private static final int TAKE_CHOSEIMAGS = 0x000002;
	private static final String TAG = "AskQuestionActivity";
	File imagefile;
	private String adress;
	private AKGridView gridView1;
	private ArrayList<HashMap<String, Object>> imageItem;
	private SimpleAdapter simpleAdapter;
	private Bitmap myBitmap1;
	private Bitmap bitmap1;
	private RecordImage voiceimageview;
	private View falseparent;

	public static ImageView playimage, delimage;

	int coin = -1;
	String answer = "";
	private PopupWindow addressPupo;
	private WheelView mViewProvince;
	private WheelView mViewCity;
	private WheelView mViewDistrict;
	private Button mBtnConfirm;
	private LinearLayout parent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application.getInstance().addActivity(this);
		setContentView(R.layout.infox_activity_askquestion);
		title = (ActivityTitle) findViewById(R.id.askQuesyionTitle);
		title.setTitle("提问");

		title.setViewVersible(title.titleBack, title.rightText);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		title.setRightTextViewText("提交");
		// player = new MediaPlayer();
		answer = getIntent().getStringExtra("userId");
		System.out.println(answer);
		initView();
		getdata();
		try {
			location = SharedPreferencesKit.getJsonObject(getApplicationContext(), Const.SP_KEY_BD_LOCAITON).getString("loc");
			adress = SharedPreferencesKit.getJsonObject(getApplicationContext(), Const.SP_KEY_BD_LOCAITON).getString("city");

			if (adress.equals("null")) {
				city = "";
				locationTextView.setText("未获取定位,请手动选择");
			} else {
				city = adress;
				locationTextView.setText(adress);
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}

		title.rightText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				submit();
			}

		});

		// Constants.changeSize(AskQuestionActivity.this, this, true);

	}

	private void getdata() {
		// getmeasuredata();
		getweatherdata();
		// getnamedata();
		Api.get("me/details", ApiParam.Empty, new ApiCallback(this, true) {

			@Override
			public void handleFailure(Exception e, String msg) {
			}

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {
					try {
						coin = result.getData().getInt("coin");
						goldEditText.setHint("金币悬赏，可用" + coin + "个金币");
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage(), e);
					}
				}
			}

		}, this);
	}

	/**
	 * 
	 * 提交问题
	 * 
	 * 
	 * @author yyh Created at 2015-10-23 下午2:18:41
	 */

	private void submit() {

		// 判断问题填写状态
		if (plantnameEditText.getText().toString() == null || plantnameEditText.getText().toString().equals("")) {
			ToastKit.showLong(this, "植物名称不能为空");
			title.rightText.setClickable(true);
			return;
		}
		if (contentEditText.getText().toString() == null || contentEditText.getText().toString().equals("")) {
			ToastKit.showLong(this, "问题描述不能为空");
			title.rightText.setClickable(true);
			return;
		}

		ApiParam param = ApiParam.create();

		if (files != null) {

			for (int i = 0; i < files.size(); i++) {
				int j = i + 1;
				String s = "pic_" + j;
				param.addParam(s, files.get(i));
			}
		}

		if (audioRecorder.getFileName() != null) {
			audioFile = new File(audioRecorder.getFilePath());
			if (audioFile != null) {
				param.addParam("voice", audioFile);
			}
		}
		param.addParam("name", plantnameEditText.getText().toString());
		param.addParam("content", contentEditText.getText().toString());

		if (weatherEditText.getText().toString() == null || weatherEditText.getText().toString().equals("")) {

		} else {
			param.addParam("weather", weatherEditText.getText().toString());
		}

		if (usewhatEditText.getText().toString() == null || usewhatEditText.getText().toString().equals("")) {

		} else {
			param.addParam("measure", usewhatEditText.getText().toString());
		}

		if (goldEditText.getText().toString() == null || goldEditText.getText().toString().equals("")) {
			param.addParam("gold", 0);
		} else {
			param.addParam("gold", Integer.parseInt(goldEditText.getText().toString()));
		}
		param.addParam("location", location);
		param.addParam("area", city);

		if (answer != null && !answer.equals("")) {

			param.addParam("answer", answer);

		}

		title.rightText.setClickable(false);
		Api.post("qa/ask", param, new ApiCallback(AskQuestionActivity.this) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {
					Intent intent = new Intent();
					intent.setAction(Const.REFLASH);
					AskQuestionActivity.this.sendBroadcast(intent);
					title.rightText.setClickable(true);
					finish();

				} else {
					if (TextUtils.isEmpty(result.getMsg())) {
						ToastKit.showShort(mContext, "提交失败");
					} else {
						ToastKit.showShort(mContext, result.getMsg());
					}
				}

				title.rightText.setClickable(true);
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				title.rightText.setClickable(true);
				ToastKit.showShort(mContext, "提交失败");
			}
		}, AskQuestionActivity.this);

	}

	/**
	 * 绑定控件
	 * 
	 * 
	 * @author lkx Created at 2015-10-6 下午3:38:39
	 */
	private void initView() {
		locationTextView = (TextView) findViewById(R.id.mylocation);
		plantnameEditText = (EditText) findViewById(R.id.plantName);
		weatherEditText = (EditText) findViewById(R.id.textViewweather);
		usewhatEditText = (EditText) findViewById(R.id.textfertilization);
		goldEditText = (EditText) findViewById(R.id.textGold);
		contentEditText = (EditText) findViewById(R.id.editText1);
		playimage = (ImageView) findViewById(R.id.id_play);
		delimage = (ImageView) findViewById(R.id.id_del);
		playimage.setOnClickListener(this);
		delimage.setOnClickListener(this);

		listweather = new ArrayList<String>();
		listname = new ArrayList<String>();
		listmeasure = new ArrayList<String>();
		files = new ArrayList<>();

		goldEditText.setFilters(new InputFilter[] { new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				try {
					int input = Integer.parseInt(dest.toString() + source.toString());
					if (isInRange(0, coin, input))
						return null;
				} catch (NumberFormatException nfe) {
				}
				return "";
			}

			private boolean isInRange(int a, int b, int c) {
				return b > a ? c >= a && c <= b : c >= b && c <= a;
			}
		} });

		findViewById(R.id.id_namelayout).setOnClickListener(this);
		findViewById(R.id.id_weatherlayout).setOnClickListener(this);
		findViewById(R.id.id_measurelayout).setOnClickListener(this);
		findViewById(R.id.id_goldlayout).setOnClickListener(this);
		findViewById(R.id.id_locationlayout).setOnClickListener(this);
		findViewById(R.id.askQuestion_takePhoto).setOnClickListener(this);
		// findViewById(R.id.askQuestion_chooseImg).setOnClickListener(this);

		findViewById(R.id.id_imagelayout).setOnClickListener(this);

		voiceimageview = (RecordImage) findViewById(R.id.askQuestion_voice);

		audioRecorder = new AudioRecorder();

		voiceimageview.setAudioRecord(audioRecorder);

		gridView1 = (AKGridView) findViewById(R.id.gridView1);

		imageItem = new ArrayList<HashMap<String, Object>>();

		simpleAdapter = new SimpleAdapter(this, imageItem, R.layout.infox_griditem_imageview, new String[] { "itemImage" },
				new int[] { R.id.imageView1 });
		simpleAdapter.setViewBinder(new ViewBinder() {
			@Override
			public boolean setViewValue(View view, Object data, String textRepresentation) {
				if (view instanceof ImageView && data instanceof Bitmap) {
					ImageView i = (ImageView) view;
					i.setImageBitmap((Bitmap) data);
					return true;
				}
				return false;
			}
		});
		gridView1.setAdapter(simpleAdapter);

		gridView1.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

				dialog(position);

			}
		});
		// voiceimageview.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// // TODO Unfinish
		// ToastKit.showShort(getApplicationContext(), Const.UN_FINISH_ALERT);
		// }
		// });
		// voiceimageview.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View arg0, MotionEvent arg1) {
		//
		// switch (arg1.getAction()) {
		// case MotionEvent.ACTION_UP:
		//
		// // if (!starting) {
		// voiceok = true;
		// mediaRecorder.stop();
		// mediaRecorder.release();
		// voiceimageview.setImageResource(R.drawable.infox_start);
		// mediaRecorder = null;
		//
		// // }
		//
		// break;
		//
		// case MotionEvent.ACTION_DOWN:
		// // if (voiceok) {
		// // starting=true;
		// // final MediaPlayer mp = new MediaPlayer();
		// // try {
		// // mp.setDataSource(audioFile.getPath());
		// //
		// // mp.prepare();
		// //
		// // mp.start();
		// // } catch (IllegalArgumentException e) {
		// // // TODO Auto-generated catch block
		// // e.printStackTrace();
		// // } catch (SecurityException e) {
		// // // TODO Auto-generated catch block
		// // e.printStackTrace();
		// // } catch (IllegalStateException e) {
		// // // TODO Auto-generated catch block
		// // e.printStackTrace();
		// // } catch (IOException e) {
		// // // TODO Auto-generated catch block
		// // e.printStackTrace();
		// // }
		// //
		// // voiceimageview.setClickable(false);
		// // mp.setOnCompletionListener(new OnCompletionListener() {
		// //
		// // @Override
		// // public void onCompletion(MediaPlayer arg0) {
		// // // TODO Auto-generated method stub
		// // starting=false;
		// // voiceimageview.setClickable(true);
		// // mp.release();
		// //
		// // }
		// // });
		// //
		// // } else {
		// voiceimageview.setImageResource(R.drawable.infox_voice_green);
		// getvoice();
		// // }
		// break;
		// case MotionEvent.ACTION_CANCEL:
		// // 按钮弹起逻辑
		// mediaRecorder.stop();
		// mediaRecorder.release();
		// voiceimageview.setImageResource(R.drawable.infox_start);
		// mediaRecorder = null;
		// break;
		//
		// }
		//
		// return true;
		// }
		// });

		rootparent = (LinearLayout) findViewById(R.id.id_rootparent);

	}

	protected void dialog(final int position) {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确认移除已添加图片吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				imageItem.remove(position);
				files.remove(position);
				simpleAdapter.notifyDataSetChanged();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private void initPupoVindow(ArrayList<String> list) {
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_pupopwindow_scrollitem_layout, null);
		initData(popupWindow, list);

		// 创建一个PopupWindow
		// 参数1：contentView 指定PopupWindow的内容
		// 参数2：width 指定PopupWindow的width
		// 参数3：height 指定PopupWindow的height
		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */
	}

	private void showPupop(ArrayList<String> list) {

		initPupoVindow(list);
		mPopupWindow.showAtLocation(rootparent, Gravity.CENTER, 0, 0);

		// if (mPopupWindow == null) {
		// initPupoVindow(list);
		// mPopupWindow.showAtLocation(rootparent, Gravity.BOTTOM |
		// Gravity.CENTER_HORIZONTAL, 0, 0);
		// } else {
		// if (mPopupWindow.isShowing()) {
		// mPopupWindow.dismiss();
		// } else {
		// mPopupWindow.showAtLocation(rootparent, Gravity.BOTTOM |
		// Gravity.CENTER_HORIZONTAL, 0, 0);
		// }
		//
		// }

	}

	private void initData(View v, final ArrayList<String> list) {
		layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

		rootview = (LinearLayout) v.findViewById(R.id.mRootView);
		falseparent = v.findViewById(R.id.id_falseparent);
		falseparent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mPopupWindow.dismiss();
			}
		});

		loopView = new LoopView(this);
		TextView view = new TextView(AskQuestionActivity.this);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		lp.setMargins(0, 10, 0, 5);
		view.setLayoutParams(lp);
		view.setBackgroundResource(R.drawable.infox_send_back);
		view.setText("确   定");
		view.setTextSize(20.0f);
		view.setPadding(20, 10, 20, 10);
		view.setTextColor(Color.WHITE);
		view.setGravity(Gravity.CENTER);

		// 设置是否循环播放
		loopView.setNotLoop();
		// 滚动监听
		loopView.setListener(new LoopListener() {
			@Override
			public void onItemSelect(int item) {
				a = list.get(item);
			}
		});
		// 设置原始数据
		loopView.setArrayList(list);
		// 设置初始位置
		loopView.setPosition(0);
		// 设置字体大小
		loopView.setTextSize(18f);
		rootview.addView(loopView, layoutParams);
		rootview.addView(view);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int selectItem = loopView.selectItem();

				switch (c) {
				case 1:
					plantnameEditText.setText(list.get(selectItem));
					break;
				case 2:
					weatherEditText.setText(list.get(selectItem));
					break;
				case 3:
					usewhatEditText.setText(list.get(selectItem));
					break;
				case 4:
					goldEditText.setText(list.get(selectItem));
					break;

				}

				// mJob = list.get(selectItem);
				// doEditText.setText(list.get(selectItem));
				// Toast.makeText(AskQuestionActivity.this,
				// list.get(selectItem), 0).show();
				mPopupWindow.dismiss();
			}
		});
	}

	@Override
	public void onClick(View arg0) {

		switch (arg0.getId()) {

		case R.id.id_locationlayout:

			// Intent cityintent = new Intent(AskQuestionActivity.this,
			// Selectcity.class);
			// startActivityForResult(cityintent, 3);

			if (addressPupo == null) {
				initPopuWindow();
				if (addressPupo.isShowing()) {
					addressPupo.dismiss();
				} else {
					addressPupo.showAtLocation(findViewById(R.id.id_parent_view), Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
				}
			} else {
				if (addressPupo.isShowing()) {
					addressPupo.dismiss();
				} else {
					addressPupo.showAtLocation(findViewById(R.id.id_parent_view), Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
				}
			}

			break;

		case R.id.id_namelayout:
			// if (TextUtils.isEmpty(plantnameEditText.getText().toString())) {
			// // 更改list数据 showpopwindow
			// c = 1;
			// if (!(listname.size() > 0)) {
			// ToastKit.showShort(AskQuestionActivity.this, "暂未获取到列表，请重试");
			// getnamedata();
			//
			// } else {
			// showPupop(listname);
			// }
			// } else {
			// plantnameEditText.requestFocus();
			// }
			break;

		case R.id.id_weatherlayout:
			if (TextUtils.isEmpty(weatherEditText.getText().toString())) {
				// 更改list数据 showpopwindow
				c = 2;
				if (!(listweather.size() > 0)) {
					getweatherdata();
					ToastKit.showShort(AskQuestionActivity.this, "暂未获取到列表，请重试");
				} else {

					showPupop(listweather);
				}
			} else {
				weatherEditText.requestFocus();
			}
			break;
		case R.id.id_measurelayout:
			// if (TextUtils.isEmpty(usewhatEditText.getText().toString())) {
			// // 更改list数据 showpopwindow
			// c = 3;
			// if (!(listmeasure.size() > 0)) {
			// getmeasuredata();
			// ToastKit.showShort(AskQuestionActivity.this, "暂未获取到列表，请重试");
			// } else {
			//
			// showPupop(listmeasure);
			// }
			// } else {
			// usewhatEditText.requestFocus();
			// }

			break;
		case R.id.id_goldlayout:
			// if (TextUtils.isEmpty(((EditText)
			// findViewById(R.id.textGold)).getText().toString())) {
			// // 更改list数据 showpopwindow
			// c = 4;
			// showPupop(listglobe);
			// } else {
			goldEditText.requestFocus();
			// }
			break;

		// case R.id.askQuestion_takePhoto:
		// if (imageItem.size() >= 6) {
		// ToastKit.showShort(AskQuestionActivity.this, "最多选择6张照片");
		// return;
		// }
		//
		// Intent openCameraIntent = new
		// Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// startActivityForResult(openCameraIntent, TAKE_TAKEPHOTO);
		//
		// break;
		case R.id.id_imagelayout:

			if (imageItem.size() >= 6) {
				ToastKit.showShort(AskQuestionActivity.this, "最多选择6张照片");
				return;
			}

			new AlertDialog.Builder(AskQuestionActivity.this).setMessage("请选择上传方式")// 设置显示的内容

					.setPositiveButton("相机", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 确定按钮的响应事件

							Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(openCameraIntent, TAKE_TAKEPHOTO);

						}

					}).setNegativeButton("图库", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							Intent intent = new Intent(getApplicationContext(), ImageshowActivity.class);
							intent.putExtra("max", 6 - imageItem.size());
							startActivityForResult(intent, 100);

						}

					}).show();// 在按键响应事件中显示此对话框

			//
			// if (imageItem.size() >= 6) {
			// ToastKit.showShort(AskQuestionActivity.this, "最多选择6张照片");
			// return;
			// }
			//
			// Intent intent = new Intent(getApplicationContext(),
			// ImageshowActivity.class);
			// intent.putExtra("max", 6 - imageItem.size());
			// startActivityForResult(intent, 100);

			break;

		case R.id.id_play:

			if (audioRecorder.getFileName() != null) {
				playimage.setImageResource(R.drawable.infox_stop);

				if (player == null) {
					player = new MediaPlayer();

					try {

						player.reset();
						player.setDataSource(audioRecorder.getFilePath());
						player.prepare();
						player.start();
						playimage.setClickable(false);
						player.setOnCompletionListener(new OnCompletionListener() {

							@Override
							public void onCompletion(MediaPlayer arg0) {
								// TODO Auto-generated method stub

								player.stop();
								player.release();
								player = null;
								playimage.setImageResource(R.drawable.infox_start);
								playimage.setClickable(true);

							}
						});

					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}

			break;
		case R.id.id_del:

			if (player != null) {
				player.stop();
				player.release();
			}
			player = null;
			audioRecorder.deleteOldFile();

			playimage.setVisibility(View.GONE);
			delimage.setVisibility(View.GONE);
			playimage.setImageResource(R.drawable.infox_start);
			playimage.setClickable(true);
			voiceimageview.setVisibility(View.VISIBLE);

			break;
		case R.id.btn_confirm:
			/** 隐藏软键盘 **/
			View view = getWindow().peekDecorView();
			if (view != null) {
				InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
			}
			showSelectedResult();
			addressPupo.dismiss();
			break;

		case R.id.id_parent:

			addressPupo.dismiss();
			break;

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null || data.equals("")) {
			return;
		}

		switch (requestCode) {
		case TAKE_TAKEPHOTO:

			if (resultCode == RESULT_OK) {

				Bitmap myBitmap = data.getParcelableExtra("data");
				myBitmap1 = compressImage(myBitmap);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("itemImage", myBitmap1);
				imageItem.add(map);
				saveBitmapFile(myBitmap);
				myBitmap = null;
				myBitmap1 = null;
				simpleAdapter.notifyDataSetChanged();

			}

			break;
		// case TAKE_CHOSEIMAGS:
		//
		// if (resultCode == RESULT_OK) {
		// Uri uri = data.getData();
		// Log.e("uri", uri.toString());
		// ContentResolver cr = this.getContentResolver();
		// try {
		// BitmapFactory.Options options = new BitmapFactory.Options();
		// options.inSampleSize = 5;
		// Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri),
		// null, options);
		// // bitmap1 = compressImage(bitmap);
		// HashMap<String, Object> map = new HashMap<String, Object>();
		// map.put("itemImage", bitmap);
		// imageItem.add(map);
		// simpleAdapter.notifyDataSetChanged();
		//
		// saveBitmapFile(bitmap);
		//
		// } catch (FileNotFoundException e) {
		// Log.e("Exception", e.getMessage(), e);
		// }
		// }
		//
		// break;

		case 3:
			if (resultCode == -1) {
				String adress = data.getStringExtra("adress");

				city = data.getStringExtra("city");
				locationTextView.setText(adress);
			}

			break;
		case 100:
			if (resultCode == 100) {
				String str = data.getStringExtra("image");
				if (str != null && !str.equals("")) {
					String[] image = str.split(";");

					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inSampleSize = 2;
					Bitmap bitmap;
					for (int i = 0; i < image.length; i++) {
						String path = image[i];
						// Drawable drawable = Drawable.createFromPath(path);

						bitmap = getSmallBitmap(path);
						//
						// bitmap = BitmapFactory.decodeFile(path, options);
						// bitmap = compressImage(bitmap);
						saveBitmapFile(bitmap);
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put("itemImage", bitmap);
						imageItem.add(map);

						bitmap = null;

					}
					simpleAdapter.notifyDataSetChanged();

				}
			}
			break;

		}
	}

	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 384, 640);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(filePath, options);
	}

	// 计算图片的缩放值
	public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height / (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	public void saveBitmapFile(Bitmap bitmap) {
		try {
			imagefile = File.createTempFile("letter", ".jpg");
		} catch (IOException e1) {
			Log.e(TAG, e1.getMessage(), e1);
		}

		try {
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imagefile));
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
			files.add(imagefile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 90;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			options -= 10;// 每次都减少10
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中

		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		image = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return image;
	}

	/**
	 * 
	 * 获取最近使用
	 * 
	 * 
	 * @author yyh Created at 2015-10-22 下午4:47:19
	 */
	private void getmeasuredata() {
		Api.data("fertilizer_list.json", new ApiCallback(AskQuestionActivity.this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				JSONArray jsonArray = result.getDatas();
				for (int i = 0; i < jsonArray.length(); i++) {
					try {
						listmeasure.add(jsonArray.getJSONObject(i).getString("title"));
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage(), e);
					}

				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {
			}
		}, AskQuestionActivity.this);

	}

	/**
	 * 
	 * 获取天气列表
	 * 
	 * 
	 * @author yyh Created at 2015-10-22 上午11:40:06
	 */

	private void getweatherdata() {
		Api.data("weather_type_list.json", new ApiCallback(AskQuestionActivity.this) {

			@Override
			public void handleSuccess(ApiResult result) {
				JSONArray jsonArray = result.getDatas();
				for (int i = 0; i < jsonArray.length(); i++) {
					try {
						listweather.add(jsonArray.getString(i));
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage(), e);
					}

				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, AskQuestionActivity.this);

	}

	/**
	 * 
	 * 获取作物名列表
	 * 
	 * 
	 * @author yyh Created at 2015-10-22 上午11:40:53
	 */

	private void getnamedata() {
		Api.data("plant_list.json", new ApiCallback(AskQuestionActivity.this) {

			@Override
			public void handleSuccess(ApiResult result) {
				JSONArray jsonArray = result.getDatas();

				for (int i = 0; i < jsonArray.length(); i++) {
					try {
						listname.add(jsonArray.getJSONObject(i).getString("title"));
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage(), e);
					}
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, AskQuestionActivity.this);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (mPopupWindow != null && mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
				return false;
			} else {
				return super.onKeyDown(keyCode, event);
			}

		}
		return false;

	}

	private void initPopuWindow() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View popupWindow = inflater.inflate(R.layout.infox_choosesddress_populayout, null);
		addressPupo = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT);
		// 必须设置背景
		addressPupo.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		addressPupo.setOutsideTouchable(true); /* 设置触摸外面时消失 */

		setUpViews(popupWindow);
		setUpListener();
		setUpData();

	}

	private void setUpViews(View view) {
		mViewProvince = (WheelView) view.findViewById(R.id.id_province);
		mViewCity = (WheelView) view.findViewById(R.id.id_city);
		mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
		mBtnConfirm = (Button) view.findViewById(R.id.btn_confirm);
		parent = (LinearLayout) view.findViewById(R.id.id_parent);

	}

	private void setUpListener() {
		// 添加change事件
		mViewProvince.addChangingListener(this);
		// 添加change事件
		mViewCity.addChangingListener(this);
		// 添加change事件
		mViewDistrict.addChangingListener(this);
		// 添加onclick事件
		mBtnConfirm.setOnClickListener(this);
		parent.setOnClickListener(this);
	}

	private void setUpData() {
		// initProvinceDatas();
		// getCityList();
		// getDate(SharedPreferencesKit.getString(PerfectInformationActivity.this,
		// "address"));

		if (TextUtils.isEmpty(SharedPreferencesKit.getString(AskQuestionActivity.this, "address"))) {
			// 获取数据
			System.out.println("+++++++++++++++++++");
			Api.data("area_provincial_city_county.json", new ApiCallback(AskQuestionActivity.this) {
				@Override
				public void handleFailure(Exception e, String msg) {

				}

				@Override
				public void handleSuccess(ApiResult result) {
					SharedPreferencesKit.putString(AskQuestionActivity.this, "address", result.getDatas().toString());
					getCityList(result.getDatas().toString());

					mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(AskQuestionActivity.this, mProvinceDatas));
					// 设置可见条目数量
					mViewProvince.setVisibleItems(7);
					mViewCity.setVisibleItems(7);
					mViewDistrict.setVisibleItems(7);
					updateCities();
					updateAreas();
				}
			}, AskQuestionActivity.this);

		} else {
			getCityList(SharedPreferencesKit.getString(AskQuestionActivity.this, "address"));

			mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(AskQuestionActivity.this, mProvinceDatas));
			// 设置可见条目数量
			mViewProvince.setVisibleItems(7);
			mViewCity.setVisibleItems(7);
			mViewDistrict.setVisibleItems(7);
			updateCities();
			updateAreas();
		}

		//
		// mViewProvince.setViewAdapter(new
		// ArrayWheelAdapter<String>(PerfectInformationActivity.this,
		// mProvinceDatas));
		// // 设置可见条目数量
		// mViewProvince.setVisibleItems(7);
		// mViewCity.setVisibleItems(7);
		// mViewDistrict.setVisibleItems(7);
		// updateCities();
		// updateAreas();
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		// TODO Auto-generated method stub
		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		} else if (wheel == mViewDistrict) {
			mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			mCurrentDistrictCode = mXianjicodeDatasMap.get(mCurrentDistrictName);
		}
	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		mViewDistrict.setCurrentItem(0);
		mCurrentDistrictName = areas[0];
		mCurrentDistrictCode = mXianjicodeDatasMap.get(mCurrentDistrictName);
	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		mViewCity.setCurrentItem(0);
		updateAreas();
	}

	private void showSelectedResult() {
		String address = "";
		if (!TextUtils.isEmpty(mCurrentProviceName)) {

			mCurrentProviceCode = mShengJicodeDatasMap.get(mCurrentProviceName);
		}
		if (!TextUtils.isEmpty(mCurrentCityName)) {

			mCurrentCityCode = mShijiCodeMap.get(mCurrentCityName);
		}
		if (!TextUtils.isEmpty(mCurrentDistrictName)) {

			mCurrentDistrictCode = mXianjicodeDatasMap.get(mCurrentDistrictName);
		}
		// Toast.makeText(PerfectInformationActivity.this,
		// "当前选中:" + mCurrentProviceName + "," + mCurrentCityName + "," +
		// mCurrentDistrictName + "," + mCurrentZipCode,
		// Toast.LENGTH_SHORT).show();
		System.out.println("当前选中:" + mCurrentProviceCode + "," + mCurrentCityCode + "," + mCurrentDistrictCode);
		if (!TextUtils.isEmpty(mCurrentProviceName)) {
			mCurrentProviceCode = mShengJicodeDatasMap.get(mCurrentProviceName);
			address = mCurrentProviceName;
			if (!TextUtils.isEmpty(mCurrentCityName)) {
				address = address + mCurrentCityName;
				mCurrentCityCode = mShijiCodeMap.get(mCurrentCityName);
				if (!TextUtils.isEmpty(mCurrentDistrictName) && (!mCurrentDistrictName.equals("--"))) {
					address = address + mCurrentDistrictName;
					mCurrentDistrictCode = mXianjicodeDatasMap.get(mCurrentDistrictName);
				}
			}
			city = mCurrentCityName;
			locationTextView.setText(address);
		}

	}

}
